#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python基础：模块和包
"""

# 导入标准库模块
import math
import random
import datetime
import os

# 导入特定函数
from collections import Counter, defaultdict
from functools import reduce

# 导入自定义模块（如果存在）
try:
    # 假设我们有一个自定义模块
    import sys
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    # from my_module import my_function  # 示例
except ImportError:
    pass

def demonstrate_standard_libraries():
    """演示标准库的使用"""
    print("=== 标准库示例 ===")
    
    # math模块
    print(f"π的值: {math.pi}")
    print(f"sqrt(16): {math.sqrt(16)}")
    print(f"sin(π/2): {math.sin(math.pi/2)}")
    
    # random模块
    print(f"随机浮点数 (0-1): {random.random()}")
    print(f"随机整数 (1-10): {random.randint(1, 10)}")
    choices = ['苹果', '香蕉', '橙子']
    print(f"随机选择: {random.choice(choices)}")
    
    # datetime模块
    now = datetime.datetime.now()
    print(f"当前时间: {now}")
    print(f"格式化时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")

def demonstrate_collections():
    """演示collections模块"""
    print("\n=== Collections模块示例 ===")
    
    # Counter计数器
    text = "hello world"
    char_count = Counter(text)
    print(f"字符计数: {char_count}")
    print(f"最常见的字符: {char_count.most_common(3)}")
    
    # defaultdict默认字典
    dd = defaultdict(list)
    dd['fruits'].append('苹果')
    dd['fruits'].append('香蕉')
    dd['vegetables'].append('胡萝卜')
    print(f"默认字典: {dict(dd)}")

def demonstrate_list_comprehensions():
    """演示列表推导式"""
    print("\n=== 列表推导式示例 ===")
    
    # 基本列表推导式
    squares = [x**2 for x in range(10)]
    print(f"平方数: {squares}")
    
    # 带条件的列表推导式
    even_squares = [x**2 for x in range(10) if x % 2 == 0]
    print(f"偶数的平方: {even_squares}")
    
    # 嵌套列表推导式
    matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
    print(f"矩阵: {matrix}")

def demonstrate_lambda_and_map():
    """演示lambda和map函数"""
    print("\n=== Lambda和Map示例 ===")
    
    # lambda函数
    add = lambda x, y: x + y
    print(f"Lambda加法: {add(3, 5)}")
    
    # map函数
    numbers = [1, 2, 3, 4, 5]
    squared = list(map(lambda x: x**2, numbers))
    print(f"映射平方: {squared}")
    
    # filter函数
    evens = list(filter(lambda x: x % 2 == 0, numbers))
    print(f"过滤偶数: {evens}")
    
    # reduce函数
    product = reduce(lambda x, y: x * y, numbers)
    print(f"累积乘积: {product}")

def demonstrate_file_path_operations():
    """演示文件路径操作"""
    print("\n=== 文件路径操作示例 ===")
    
    # 获取当前工作目录
    cwd = os.getcwd()
    print(f"当前工作目录: {cwd}")
    
    # 列出目录内容
    files = os.listdir('../../python_basics')
    print(f"当前目录文件: {files[:5]}...")  # 只显示前5个
    
    # 路径拼接
    path = os.path.join('python_basics', '07_modules_and_packages.py')
    print(f"拼接路径: {path}")
    print(f"路径是否存在: {os.path.exists(path)}")

class Calculator:
    """简单计算器类"""
    
    @staticmethod
    def add(a, b):
        """加法"""
        return a + b
    
    @staticmethod
    def subtract(a, b):
        """减法"""
        return a - b
    
    @staticmethod
    def multiply(a, b):
        """乘法"""
        return a * b
    
    @staticmethod
    def divide(a, b):
        """除法"""
        if b == 0:
            raise ValueError("除数不能为零")
        return a / b

def demonstrate_class_usage():
    """演示类的使用"""
    print("\n=== 类使用示例 ===")
    
    calc = Calculator()
    print(f"加法: 10 + 5 = {calc.add(10, 5)}")
    print(f"减法: 10 - 5 = {calc.subtract(10, 5)}")
    print(f"乘法: 10 * 5 = {calc.multiply(10, 5)}")
    try:
        print(f"除法: 10 / 5 = {calc.divide(10, 5)}")
        print(f"除法: 10 / 0 = {calc.divide(10, 0)}")
    except ValueError as e:
        print(f"错误: {e}")

if __name__ == "__main__":
    demonstrate_standard_libraries()
    demonstrate_collections()
    demonstrate_list_comprehensions()
    demonstrate_lambda_and_map()
    demonstrate_file_path_operations()
    demonstrate_class_usage()